package xcmg.syn.util;

import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class GeoUtil {
    /**
     * 默认地球半径
     */
    private static double EARTH_RADIUS = 6371;

    private GeoUtil() {
    }

    /**
     * @param longitude
     * @param latitude
     * @param dis       单位km
     * @return
     */
    public static Map<String, String> returnLLSquarePoints(double longitude, double latitude, double dis) {
        Map<String, String> result = new HashMap<>(4);
        //先计算查询点的经纬度范围
        double r = 6371;//地球半径千米
        double dlng = 2 * Math.asin(Math.sin(dis / (2 * r)) / Math.cos(latitude * Math.PI / 180));
        dlng = dlng * 180 / Math.PI;//角度转为弧度
        double dlat = dis / r;
        dlat = dlat * 180 / Math.PI;
        double minlat = latitude - dlat;
        double maxlat = latitude + dlat;
        double minlng = longitude - dlng;
        double maxlng = longitude + dlng;
        DecimalFormat df = new DecimalFormat("#.000000");
        result.put("minLat", df.format(minlat));
        result.put("maxLat", df.format(maxlat));
        result.put("minLon", df.format(minlng));
        result.put("maxLon", df.format(maxlng));

        return result;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 返回距离，单位m
     *
     * @param poit1Lat
     * @param poit1Lon
     * @param poit2
     * @return
     */
    public static double getDistance(String poit1Lat, String poit1Lon, String poit2) {
        //数据问题，认为距离最大Double
        if (StringUtils.isEmpty(poit1Lat) || StringUtils.isEmpty(poit1Lon) || StringUtils.isEmpty(poit2)) {
            return Double.MAX_VALUE;
        }
        String[] p2 = poit2.split(",");
        if (p2.length != 2) {
            return Double.MAX_VALUE;
        }
        try {
            double lat1 = Double.parseDouble(poit1Lat);
            double lon1 = Double.parseDouble(poit1Lon);
            double lat2 = Double.parseDouble(p2[1]);
            double lon2 = Double.parseDouble(p2[0]);
            double radLat1 = rad(lat1);
            double radLat2 = rad(lat2);
            double a = radLat1 - radLat2;
            double b = rad(lon1) - rad(lon2);
            double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
            s = s * EARTH_RADIUS * 1000;
            s = Math.round(s * 10000) / 10000;
            return s;
        } catch (Exception e) {
            return Double.MAX_VALUE;
        }
    }
}
